package com.jaya.budan.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.activity.GD_Map_Activity;
import com.jaya.budan.activity.PhotoAlbum_Activity;
import com.jaya.budan.adapter.LV_DongtaiTG_Adapter;
import com.jaya.budan.base.BaseFragment;
import com.jaya.budan.bean.ListUser_Information;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ImageUtils;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.MyListView;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class Square_Nearby_Fragment extends BaseFragment implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private MyListView main_listview;
    private ImageView fabtn_geren_main;
    private String access_token, currentUploadPath;
    private List<ListUser_Information> user_informations;
    private static final int TAKE_PHOTO = 0;
    private static final int RESULT_REQUEST_CODE=2;
    private Uri photoUri;
    private PullToRefreshLayout topic_pull_layout;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_square_nearby, container, false);
        main_listview = view.findViewById(R.id.main_listview);
        fabtn_geren_main = view.findViewById(R.id.fabtn_geren_main);
        topic_pull_layout = view.findViewById(R.id.topic_pull_layout);
        Bundle bundle = getArguments();
        access_token = bundle.getString("access_token");
        postData();
        fabtn_geren_main.setOnClickListener(this);
        topic_pull_layout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                topic_pull_layout.finishRefresh();//结束刷新
            }

            @Override
            public void loadMore() {
                topic_pull_layout.finishLoadMore();//结束加载更多
            }
        });
        return view;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_main_ditu:
                Intent intent = new Intent(getActivity(), GD_Map_Activity.class);
                startActivity(intent);
                break;
            case R.id.fabtn_geren_main:
                fabtn_geren_main.setVisibility(View.GONE);
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_geren_main_fabtn)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setOutsideTouchable(false)
                        .setBackgroundAlpha(0.7f)
                        .build(getActivity())
                        .showAsDown(v);
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.square_list_Url + access_token + "&circle_id=0&type=3&limit=10&page=1", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("square_nearby", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        user_informations = gson.fromJson(info.toString(), new TypeToken<List<ListUser_Information>>(){}.getType());
                        Log.d("square_nearby", JSON.toJSONString(user_informations));
                        main_listview.setAdapter(new LV_DongtaiTG_Adapter(getActivity(), user_informations, 2, access_token));
                    } else {
                        ToolUtils.showToast(getActivity(), message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(getActivity(), "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(getActivity()).add(request);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_geren_main_fabtn:
                ImageView iv_geren_fabtn_guanbi = view.findViewById(R.id.iv_geren_fabtn_guanbi);
                ImageView iv_geren_fabtn_paishe = view.findViewById(R.id.iv_geren_fabtn_paishe);
                ImageView iv_geren_fabtn_xuanze = view.findViewById(R.id.iv_geren_fabtn_xuanze);
                iv_geren_fabtn_guanbi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        fabtn_geren_main.setVisibility(View.VISIBLE);
                    }
                });
                iv_geren_fabtn_paishe.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            //只是加了一个uri作为地址传入
                            Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            try {
                                File photoFile = createImgFile();
                                photoUri = Uri.fromFile(photoFile);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            cropPhoto(photoUri);
                            intent2.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);//指定了存储的路径的uri，那么返回的data就为null
                            startActivityForResult(intent2, TAKE_PHOTO);
                        } else {
                            ToolUtils.showToast(getActivity(), "SD卡不可用~");
                        }
                    }
                });
                iv_geren_fabtn_xuanze.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        Intent intent = new Intent(getActivity(), PhotoAlbum_Activity.class);
                        intent.putExtra("access_token", access_token);
                        intent.putExtra("bucket", "square");
                        intent.putExtra("cos_type", 1);
                        startActivity(intent);
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 自定义图片名，获取照片的file
     */
    private File createImgFile() throws IOException {
        //创建文件
        String fileName = "img_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";//确定文件名
        File dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = getActivity().getExternalCacheDir();
        } else {
            dir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir.getPath(), fileName);
        if (tempFile.exists()) {
            tempFile.delete();
        }
        tempFile.createNewFile();
        //获取文件路径
        currentUploadPath = tempFile.getAbsolutePath();
        return tempFile;
    }

    /**
     * 调用系统的裁剪
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    //将图片添加进手机相册
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(photoUri);
        getActivity().sendBroadcast(mediaScanIntent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK && data != null) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    galleryAddPic();
                    break;
                case RESULT_REQUEST_CODE:
                    Log.d("fill", "111" + currentUploadPath);
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap head = extras.getParcelable("data");
//                        Bitmap bitmap = BitmapFactory.decodeFile(currentUploadPath);
//                            iv_fill_information_icon.setImageBitmap(bitmap);
                        if (head != null) {
//                                iv_fill_information_icon.setImageBitmap(head);//按钮加载图片
                            ImageUtils.bitmapToBase64(head);//base64加密
                            try {
                                ImageUtils.saveBitmapToFile(head, currentUploadPath);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        new PhotoAlbum_Activity().upload(currentUploadPath, "square", access_token, getActivity(), 1);
                                    }
                                });
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
